package com.by.basicgateway.intercept.exception;

import cn.hutool.core.bean.BeanUtil;
import com.by.toolkit.enums.ErrorCodeEnum;
import com.by.toolkit.exceptions.ServiceException;
import com.by.toolkit.model.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.Map;

import static com.by.toolkit.utils.ExceptionUtil.getStackTrace;

/**
 * @author Tian Wei
 * @version 1.0
 * @date 2023/12/29 4:29 PM
 */
@Slf4j
public class CustomizeErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        //网关错误日志收集
        Throwable throwable = super.getError(request);
        String path = request.uri().getPath();
        String host = request.uri().getHost();
        log.error("[CustomizeErrorAttributes][handle] gateway请求异常,请求地址:{},请求路径:{},异常原因:{}", host, path, getStackTrace(throwable));
        Resp<Object> resp;
        if (throwable instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) throwable;
            resp = Resp.builder()
                    .code(serviceException.getCode())
                    .msg(serviceException.getMsg())
                    .build();
        } else {
            resp = Resp.builder().code(ErrorCodeEnum.GATE_ERROR.getErrorCode())
                    .msg(ErrorCodeEnum.GATE_ERROR.getErrorMessage())
                    .build();
        }
        Map<String, Object> resultMap = BeanUtil.beanToMap(resp,false,true);
        resultMap.put("status", request.exchange().getResponse().getStatusCode().value());
        return resultMap;
    }
}
